package com.qsd.orange.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.system.SystemUtil;
import com.qsd.orange.global.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 资源上传
 * @Author Esion
 * @Date 2020/9/24 18:19
 * @Version 1.0
 */
@RestController
@RequestMapping("system/resource/image")
public class SystemResourceController {

    public static final String IMAGE_PATH = SystemUtil.get("user.dir");

    @PostMapping
    public R updateImage(MultipartFile file){
        String temp = file.getName();
        System.out.println(temp);
        temp = "png";
        String name = System.currentTimeMillis() + "." + temp;
        BufferedOutputStream outputStream = null;
        try(InputStream inputStream = file.getInputStream();) {
            File f = new File(IMAGE_PATH, name);
            if (!f.exists()){
                f.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(f);
            outputStream = fileWriter.getOutputStream();
            IoUtil.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.success().data("image", name);
    }

    @GetMapping("{name}")
    public void show(@PathVariable("name") String name, HttpServletResponse response) {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(IMAGE_PATH, name));
            response.setContentType("image/png");
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
